import os.path
import shutil
from datetime import datetime

import aiofiles
import falcon

from WebBackend.middleware.virtualWorldGate_Chuche import login_require
from WebBackend.store.ConfigurationStore import ConfigurationStore
from WebBackend.utils.writeFile import write_file_async
from WebBackend.utils import mylog
import App_setting as setting


@falcon.before(login_require)
class ConfigFilesAPI:
    def __init__(self, cs: ConfigurationStore = None):
        self.config_store = cs

    async def on_get(self, req: falcon.Request, resp: falcon.Response):
        target = req.params.get('name')
        if target == 'vsftpd.conf':
            target_path = self.config_store.config_file_path
        elif target == 'smb.conf':
            target_path = '/etc/samba/smb.conf'
        else:
            raise falcon.HTTPBadRequest(title="请求参数错误：name值不对")
        #############################################
        mylog.info(f' Sending config file:{target_path} to {req.remote_addr}')
        stream = await aiofiles.open(target_path, 'r')
        resp.text = await stream.read()

    async def on_post(self, req, resp):
        target = req.params.get('name')
        if target == 'vsftpd.conf':
            target_path = self.config_store.config_file_path
        elif target == 'smb.conf':
            target_path = '/etc/samba/smb.conf'
        else:
            raise falcon.HTTPNotFound(title='文件不存在')
        #############################################
        data: bytes = await req.stream.read()
        now = datetime.now()
        new_file_name = f'{target}.[{now.strftime("%Y%m%d_%H%M%S")}-fullEdit-backup].txt'
        shutil.copy(target_path,
                    os.path.join(setting.path.dir_conf_directEdit_backup, new_file_name))
        await write_file_async(target_path, data.decode(), 'w')
        self.config_store.reload_store()
        mylog.info(f' Rewriting config file:{target_path} from {req.remote_addr}')
        resp.text = 'ok'

    async def on_delete(self, req: falcon.Request, resp: falcon.Response):
        target = req.params.get('name')
        if target == 'vsftpd.conf':
            target_path = self.config_store.config_file_path
            backup_path = setting.path.file_vsftpd_conf_local_backup
        elif target == 'smb.conf':
            target_path = setting.path.file_samba_conf
            backup_path = setting.path.file_samba_conf_prog_backup
        else:
            raise falcon.HTTPNotFound(title='文件不能存在')
        mylog.info(f' Deleting config file:{target_path} to {req.remote_addr}')
        now = datetime.now()
        new_file_name = f'{target}.[{now.strftime("%Y%m%d_%H%M%S")}-delete-backup].txt'
        shutil.copy(target_path,
                    os.path.join(setting.path.dir_conf_delete_backup, new_file_name))
        shutil.copy(backup_path, target_path)
        if target == 'vsftpd.conf':
            self.config_store.reload_store()
        elif target == 'smb.conf':
            pass
        resp.text = 'ok'
